from django.core.paginator import Paginator
from django.shortcuts import render , HttpResponse ,redirect
from django.views import View
from orders.models import OrderInfo
from users.forms import RegisterForms , LoginForms
from users.models import User , Address
from django.http import JsonResponse , HttpResponseForbidden
from django_redis import get_redis_connection
from django.contrib.auth import login , authenticate , logout
from django.contrib.auth.mixins import LoginRequiredMixin
from utils.response_code import RETCODE
from utils.view import LoginRequiredMixinJosn
from users.utils import generate_verify_email_url , check_verify_email_url
from django.core.mail import send_mail
from JiXuShopSystem import settings
import json
import re
from goods.models import SKU

# 注册视图
class RegisterView(View):
    def get(self , request):

        return render(request , 'register.html')

    def post(self , request):


        # 将用户数据传入forms组件进行校验
        register_forms = RegisterForms(request.POST)

        if register_forms.is_valid():
            # 注册信息无误
            username = register_forms.cleaned_data.get('username')
            password = register_forms.cleaned_data.get('password')
            mobile = register_forms.cleaned_data.get('mobile')
            client_code = register_forms.cleaned_data.get('sms_code')

            redis_conn = get_redis_connection('var_code')
            server_code = redis_conn.get('image_%s' % mobile)


            # 判断该电话是否已经注册
            if User.objects.filter(mobile=mobile):
                return render(request, 'register.html', {"sms_code_errmsg": "该手机号已注册"})



            # 判断短信验证是否失效
            if server_code is None:
                return render(request , 'register.html' , {"sms_code_errmsg":"短信验证码失效"})


            # 判断短信验证码是否正确
            # if server_code.decode() != client_code:
            #     return render(request , 'register.html' , {"sms_code_errmsg":"短信验证码错误"})

            # 保存用户数据入库
            user = User.objects.create_user(username=username , password=password , mobile = mobile)

            login(request , user)

            return redirect('login')

        else:
            # 获得forms组件的异常信息
            content = {"forms_err_msg" : register_forms.errors}
            return render(request , 'register.html' , content)


# 登录视图
class LoginView(View):
    def get(self , request):
        return render(request , 'login.html' )

    def post(self, request):
        login_form = LoginForms(request.POST)

        if login_form.is_valid():
            username = login_form.cleaned_data.get('username')
            password = login_form.cleaned_data.get('password')
            remembered = login_form.cleaned_data.get('remembered')

            if not all([username, password]):
                return HttpResponse('缺少必要的参数')

            # 通过认证模块到数据库中进行获取用户数据
            user = authenticate(username=username, password=password)

            # 判断在数据库中是否能够查询到用户数据
            if user is None:
                return render(request, 'login.html', {'account_errmsg': '用户名或者密码错误'})

            # 状态保持
            login(request, user)

            # 判断用户是否选择记住登录的状态
            if remembered:
                # 用户选择记住登录状态 ， 状态默认保存14天
                request.session.set_expiry(None)
            else:
                # 用户状态不保存 ， 关闭浏览器 ， 数据销毁
                request.session.set_expiry(0)

            next = request.GET.get('next')
            if next:
                # next 有值，重定向到指定的 url
                response = redirect(next)
            else:
                # 响应首页
                response = redirect('index')

            # 将获取到的 用户名写入到 Cookie 中
            response.set_cookie('username', user.username, 3600)
            return response
        else:
            context = {'forms_errors': login_form.errors}
            return render(request, 'login.html', context=context)


# 校验用户名是否存在
class UsernameCount(View):
    def get(self , request , username):
        # 根据参数从数据库获取数据
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code':200 , 'errmsg':"OK" , 'count':count})


# 退出视图
class LogoutView(View):
    def get(self , request):

        # 删除用户数据
        logout(request)

        # 删除cookies中的用户名
        response = redirect("index")
        response.delete_cookie('username')

        return response


# 用户中心
class UserInfoCenterView(LoginRequiredMixin,View):
    def get(self , request):

        context = {
            'username' : request.user.username,
            'mobile' : request.user.mobile,
            'email' : request.user.email,
            'email_active' : request.user.email_active,

        }

        return render(request , 'user_center_info.html' ,context)


# 发送邮箱
class EmailView(LoginRequiredMixinJosn,View):
    def put(self , request):
        email_json = json.loads(request.body.decode())
        email = email_json.get('email')
        id = request.user.id

        # 将email保存到redis数据库
        redis_conn = get_redis_connection('var_code')
        redis_conn.setex('email_%s' % id , 3600 , email)



        # 校验数据
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',email):
            return HttpResponseForbidden("邮箱参数有误")

        # 保存邮箱到数据库中
        request.user.email = email
        request.user.save()


        # 发送邮箱
        subject = '几许商城邮箱验证'
        # 调用生成加密验证邮箱连接
        veerify_url = generate_verify_email_url(request.user)
        html_message = f'<p>您的邮箱为：{email} , 请点击链接进行验证激活邮箱</p>' \
                       f'<p><a href="{veerify_url}">{veerify_url}</p>'
        send_mail(subject, '', from_email=settings.EMAIL_FROM,
                  recipient_list=[email], html_message=html_message)



        return HttpResponse({
            'code':RETCODE.OK,
            'errmsg' :'OK',
        })


# 校验邮箱信息
class VerifyEmailView(LoginRequiredMixin,View):
    def get(self , request):
        token = request.GET.get('token')
        if not token:
            return HttpResponseForbidden('缺少必要参数')


        user= check_verify_email_url(token)
        if not user:
            return HttpResponseForbidden("用户不存在")

        # 判断邮箱是否验证
        if user.email_active == 0:
            # 邮箱没有验证

            # 获取redis数据库中的邮箱
            redis_conn = get_redis_connection('var_code')
            try:
                email = redis_conn.get('email_%s' % user.id).decode()
            except:
                return HttpResponseForbidden("参数错误")

            if not email:
                return HttpResponseForbidden("邮箱验证失效")

            # 删除redis中的邮箱
            redis_conn.delete('email_%s' % user.id)



            user.email_active = 1
            user.save()

            return redirect('验证成功')
        else:
            return HttpResponseForbidden("该邮箱已经注册")


# 设置收货地址
class AddressView(LoginRequiredMixin,View):
    def get(self , request):
        login_user = request.user

        # 从数据库中获取收货地址信息
        addresses = Address.objects.filter(user=login_user , is_delete=False)

        address_list = []
        for address in addresses:
            address_dict = {
                'id': address.id,
                'receiver': address.receiver,
                'province': address.province.area_name,
                'city': address.city.area_name,
                'district': address.district.area_name,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email,
            }
            address_list.append(address_dict)

        context = {
            # 创建的收货地址
            'addresses' : address_list,
            # 默认收货地址的ID
            'default_address_id' : login_user.default_address_id,
            # 已创建地址的数量
            'count' : addresses.count()
        }


        return render(request , 'user_center_site.html' , context=context)


# 修改密码
class ChangePasswordView(LoginRequiredMixin,View):
    def get(self , request):
        return render(request , 'user_center_pass.html')

    def post(self , request):
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        new_password2 = request.POST.get('new_password2')



        if not all([old_password,new_password2,new_password]):
            return HttpResponseForbidden("缺少必要参数")

        if not request.user.check_password(old_password):
            return render(request, 'user_center_pass.html', {'origin_password_errmsg': '旧密码不正确'})

        if new_password != new_password2:
            return HttpResponseForbidden("两次输入密码不一致")

        if not re.match(r'^[0-9A-Za-z]{6,20}$' , new_password):
            return HttpResponseForbidden("密码格式不正确")

        if old_password == new_password:
            return HttpResponseForbidden("两次密码不能相同")

        request.user.set_password(new_password)
        request.user.save()

        logout(request)
        response = redirect('login')
        response.delete_cookie('username')
        return response


# 保存收货地址
class SaveAddressView(LoginRequiredMixinJosn,View):
    def post(self , request):
        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        if not all([receiver,province_id,city_id,district_id,place,mobile]):
            return HttpResponseForbidden("缺少必要数据")

        if not re.match(r'^1[3-9]\d{9}$' , mobile):
            return HttpResponseForbidden("号码不正确")

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return HttpResponseForbidden('固定电话输入有误')

        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return HttpResponseForbidden('邮箱输入有误')


        # 将数据保存到数据库中
        address = Address.objects.create(
            user=request.user,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email,
        )
        address_dict = {
            'id': address.id,
            'receiver': address.receiver,
            'province': address.province.area_name,
            'city': address.city.area_name,
            'district': address.district.area_name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '新增地址成功', 'address': address_dict})


# 修改/删除地址
class UpdataAddressView(LoginRequiredMixin,View):
    # 修改地址
    def put(self , request , address_id):
        # 获取数据
        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return HttpResponseForbidden("缺少必要数据")

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseForbidden("号码不正确")

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return HttpResponseForbidden('固定电话输入有误')

        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return HttpResponseForbidden('邮箱输入有误')

        # 保存数据
        Address.objects.filter(id=address_id).updata(
            user=request.user,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email,
        )

        # 将数据返回到前端
        address = Address.objects.get(id = address_id)
        address_dict = {
            'id': address.id,
            'receiver': address.receiver,
            'province': address.province.area_name,
            'city': address.city.area_name,
            'district': address.district.area_name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '修改地址成功', 'address': address_dict})

    # 删除地址
    def delete(self , request , address_id):
        address = Address.objects.get(id = address_id)
        address.is_delete = True
        address.save()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '删除地址成功'})


# 设置用户默认地址
class DefaultAddressView(LoginRequiredMixin,View):
    def put(self , request, address_id):
        adderss = Address.objects.get(id = address_id)
        request.user.default_address = adderss
        request.user.save()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '默认地址设置成功'})


# 缓存浏览记录
class BrowseHistoriesView(LoginRequiredMixin,View):
    def get(self , request):
        redis_conn = get_redis_connection('history')
        user = request.user
        good_data = redis_conn.lrange('history_%s' % user.id, 0 , -1)
        skus = []
        for sku_id in good_data:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': str(sku.default_image)
            }
            skus.append(sku_dict)
        return JsonResponse({'code':RETCODE.OK , 'errmsg':"OK" , 'skus':skus})


    def post(self , request):
        user = request.user
        sku_id = json.loads(request.body.decode()).get('sku_id')

        try:
            SKU.objects.get(id = sku_id)
        except Exception:
            return HttpResponseForbidden("商品数据有误")

        redis_conn = get_redis_connection('history')

        # 去重处理
        redis_conn.lrem('history_%s' % user.id, 0, sku_id)
        redis_conn.lpush('history_%s' % user.id, sku_id)
        # 截取
        redis_conn.ltrim('history_%s' % user.id, 0, 100)

        return JsonResponse({'code': RETCODE.OK, 'errmsg': "OK"})



class UserOrderView(LoginRequiredMixin,View):
    def get(self , request):
        page_num = request.GET.get('page_num')
        user = request.user
        orders = user.orderinfo_set.all()
        # 获取 商品订单数据
        for order in orders:
            # 支付方式 , 1 , 2
            order.pay_method_name = OrderInfo.PAY_METHOD_CHOICES[order.pay_method - 1][1]
            # 订单状态
            order.status_name = OrderInfo.PAY_METHOD_CHOICES[order.status - 1][1]

            order.sku_list = []
            order_goods = order.skus.all()
            for order_good in order_goods:
                sku = order_good.sku
                sku.count = order_good.count
                sku.amount = sku.price * sku.count
                order.sku_list.append(sku)

        # 制作分页
        if not page_num:
            page_num = 1
        page_num = int(page_num)
        paginatot = Paginator(orders, 5)
        page_orders = paginatot.page(page_num)
        total_page = paginatot.num_pages

        context = {
            'page_orders': page_orders,
            'total_page': total_page,
            'page_num': page_num
        }

        return render(request, 'user_center_order.html', context=context)